package com.nymph.session.impl;

import com.nymph.constant.Constant;
import com.nymph.mapping.MappedStatement;
import com.nymph.session.Configuration;
import com.nymph.session.SqlSession;
import com.nymph.session.SqlSessionFactory;
import com.nymph.util.CommonUtis;
import com.nymph.util.XmlUtil;

import java.io.File;
import java.net.URL;

/**
 * @Description: This is a sample class.
 * @Author: Simon
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private final Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
        loadMappersInfo(Configuration.getProperty(Constant.MAPPER_LOCATION).replace("\\.", "/"));
    }

    @Override
    public SqlSession openSession() {
        SqlSession session = new DefaultSqlSession(this.configuration);
        return session;
    }

    private void loadMappersInfo(String dirName) {
//        URL resource = DefaultSqlSessionFactory.class.getClassLoader().getResource(dirName);
//        File mapperDir = new File(resource.getFile());
        // todo 记住 要在这里换成具体的位置
        // 你可以通过getClassLoader的方式从resources目录中获取，
        // 但同时要考虑到userMapper.xml内容中的resulType和namespace
        // 积极使用debug
        File mapperDir=new File("D:\\java-projects\\mybatis-nymph\\src\\test\\java\\dao");
        if (mapperDir.isDirectory()) {
            File[] mappers = mapperDir.listFiles();
            if (CommonUtis.isNotEmpty(mappers)) {
                for (File file : mappers) {
                    // 对文件夹继续递归
                    if (file.isDirectory()) {
                        loadMappersInfo(dirName + "/" + file.getName());

                    } else if (file.getName().endsWith(Constant.MAPPER_FILE_SUFFIX)) {
                        XmlUtil.readMapperXml(file, this.configuration);
                    }
                }
            }
        }
    }
}
